import React from 'react';
import { connect } from 'dva';
import { ConnectProps, ConnectState } from '@/models/connect';
import styles from './index.less';

export type SiderTheme = 'light' | 'dark';
export interface GlobalHeaderRightProps extends ConnectProps {
  username: string
  theme?: SiderTheme;
  layout: 'sidemenu' | 'topmenu';
}

class GlobalHeaderRight extends React.Component<GlobalHeaderRightProps> {
  componentDidMount() {
    const { dispatch } = this.props;

    if (dispatch) {
      dispatch({
        type: 'login/fetchUserInfo',
      });
    }
  }

  logout= () => {
    const { dispatch } = this.props;

    if (dispatch) {
      dispatch({
        type: 'login/logout',
      });
    }
  }

  render(): React.ReactNode {
    const { username, theme, layout } = this.props;
    let className = styles.right;

    if (theme === 'dark' && layout === 'topmenu') {
      className = `${styles.right}  ${styles.dark}`;
    }

    return (
      <div className={className}>
        <span
          className={styles.username}>您好，{username}</span>
        <span
          className={styles.logout}
          onClick={this.logout}>退出登录</span>
      </div>
    );
  }
}

export default connect(({ settings, login }: ConnectState) => ({
  username: login.username,
  theme: settings.navTheme,
  layout: settings.layout,
}))(GlobalHeaderRight);
